package com.sherlockHolmes.init.controller;

import com.sherlockHolmes.init.base.result.Ajax;
import com.sherlockHolmes.init.entity.dao.UserInfo;
import com.sherlockHolmes.init.entity.vo.PeopleNearByVO;
import com.sherlockHolmes.init.recommend.PeopleNearby;
import com.sherlockHolmes.init.service.UserInfoService;
import org.springframework.beans.BeanUtils;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.domain.geo.Metrics;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/peopleNearby")
public class PeopleNearbyController {
    @Resource
    private PeopleNearby peopleNearby;
    @Resource
    private UserInfoService userInfoService;
    /**
     * 获取附近的人
     */
    @GetMapping("/get")
    public Ajax getPeopleNearby(HttpServletRequest request){
        try{
            HttpSession session = request.getSession();
            String name = (String) session.getAttribute("username");
            GeoResults results = peopleNearby.radiusByMember(name, 150, Metrics.METERS);
            List<GeoResult> content = results.getContent();
            List<PeopleNearByVO> peopleNearByVOList=new ArrayList<>();
            content.forEach(result -> {
                RedisGeoCommands.GeoLocation d= (RedisGeoCommands.GeoLocation) result.getContent();
                d.getName();
                d.getPoint();
                Distance distance = result.getDistance();
                if(!d.getName().equals(name)){
                    UserInfo user = userInfoService.getUserByName(String.valueOf(d.getName()));//获取用户信息
                    PeopleNearByVO peopleNearByVO = new PeopleNearByVO();
                    BeanUtils.copyProperties(user,peopleNearByVO);
                    peopleNearByVO.setDistance(distance);
                    peopleNearByVOList.add(peopleNearByVO);
                }
            });
            return Ajax.success(peopleNearByVOList);
        }catch (Exception e){
            return Ajax.fail(e);
        }
    }
}
